// 定义pinia
import { defineStore } from "pinia";
// 手动封装的操作token的方法
import { getToken, removeToken, setToken } from "../utils/token-utils";
// 引入pinia的State的类型
import type { UserInfoState } from "./interface";
// 引入类型
import type { RouteRecordRaw } from "vue-router";
// 引入静态路由、任意路由、全部路由
import { staticRoutes, anyRoutes, allAsyncRoutes } from "@/router/routes";
// 引入登录、登出、获取用户信息的接口
import { loginApi, logoutApi, userInfoApi } from "@/api/login/login";
// 引入深度克隆的方法
import cloneDeep from "lodash/cloneDeep";
// 引入路由组件
import router from "@/router";

// 🐷定义过滤路由对象的函数
const filterAsyncRoutes = (
  allAsyncRoutes: Array<RouteRecordRaw>,
  routes: string[]
) => {
  return allAsyncRoutes.filter((AsyncRoutes) => {
    // 包含
    if (routes.includes(AsyncRoutes.name as string)) {
      // 如果有子路由并且子路由有长度，则继续过滤子路由
      if (AsyncRoutes.children && AsyncRoutes.children.length) {
        AsyncRoutes.children = filterAsyncRoutes(AsyncRoutes.children, routes);
      }
      return true;
    }
    // 不包含
    return false;
  });
};
// 🐷定义添加路由的函数
const addRoutes = (hasPermissionRoutes: Array<RouteRecordRaw>) => {
  hasPermissionRoutes.forEach((route) => {
    router.addRoute(route);
  });
};
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    routes: [],
    buttons: [],
    menuRoutes: [], // 用于生成导航菜单的路由列表
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const { token } = await loginApi(username, password);
      // 本地存储
      setToken(token);
      // 存储到state中
      this.token = token;
    },
    // 登出
    async logout() {
      // 发送登出的请求
      await logoutApi();
      // 清空本地存储和pinia中的数据
      this.reset();
    },
    // 获取用户信息
    async getInfo() {
      const res = await userInfoApi();
      this.name = res.name; // 用户名称
      this.avatar = res.avatar; // 用户头像
      this.buttons = res.buttons; // 按钮权限
      this.routes = res.routes; // 路由权限
      // 过滤掉未经许可的路由
      const hasPermissionRoutes = filterAsyncRoutes(
        cloneDeep(allAsyncRoutes),
        res.routes
      );
      // 将路由添加到真正的路由中
      addRoutes([...hasPermissionRoutes, anyRoutes]);
      // 用于生成导航菜单的路由列表
      this.menuRoutes = [...staticRoutes, ...hasPermissionRoutes];
    },

    // 清除用户数据
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.$reset();
    },
  },
});
